from alipay import AliPay
from django import http
from django.shortcuts import render
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
from django_redis import get_redis_connection

from apps.orders.models import OrderInfo
from apps.payment.models import Payment
from meiduo_mall import settings
from utils.response_code import RETCODE
import logging
logger = logging.getLogger("django")
"""
1.创建应用（沙箱）
2.配置密钥
    两对公钥和私钥
    应用 和 支付宝
3.下载SDK
4.按照文档开发
"""
"""
当用户完成订单之后  前端需要把订单id给后端

后端：
    1.获取订单id
    2.根据订单id查询订单
    3.创建实例对象alipay()
    4.生成order_string
    5.返回生成的url
"""

class PaymentView(LoginRequiredMixin,View):
    def get(self,request,order_id):
        # 1.获取订单id
        try:
            # 为了查询更准确，添加两个参数，一个用户，一个订单状态
            order = OrderInfo.objects.get(order_id=order_id,user=request.user,status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist:
            return http.JsonResponse({"code":RETCODE.NODATAERR,"errmsg":"暂无此订单！"})
        # 2.根据订单id查询订单
        # 3.创建实例对象alipay()
        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()


        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调URL
            app_private_key_string=app_private_key_string,
            # 支付宝的公共密钥，不要用你自己的公钥！
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",  # RSA or RSA2
            debug=settings.ALIPAY_DEBUG  # False by default
        )
        # 4.生成order_string
        subject = "美多商城_%s"%order_id
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject=subject,
            return_url=settings.ALIPAY_RETURN_URL,
        )

        alipay_url = settings.ALIPAY_URL + '?' + order_string
        # 5.返回生成的url
        return http.JsonResponse({"code":RETCODE.OK,"errmsg":"ok","alipay_url":alipay_url})


class PaymentStatusView(View):
    """
    支付完成之后，支付宝会将参数返回给后端
    后端获取参数，按照文档的要求对数据进行验证，就可以获取 支付宝交易流水号和商家订单id
    """
    def get(self,request):
        # 1.创建alipay实例
        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()

        alipy = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调URL
            app_private_key_string=app_private_key_string,
            # 支付宝的公共密钥，不要用你自己的公钥！
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",  # RSA or RSA2
            debug=settings.ALIPAY_DEBUG  # False by default
        )
        # 2.验证数据
        data = request.GET.dict()
        # sign 不能参与签名验证
        signature = data.pop("sign")

        #　verify
        success = alipy.verify(data,signature)
        if success:
            # 获取到　out_trade_no(支付宝交易号) 和 trade_no (商家订单id)
            # 支付宝交易号
            trade_no = data.get("trade_no")
            # 商家订单id
            out_trade_no = data.get("out_trade_no")
            # 订单结果保存
            Payment.objects.create(
                order_id = out_trade_no,
                trade_id = trade_no
            )
            # 修改订单状态
            OrderInfo.objects.filter(order_id=out_trade_no).update(status=OrderInfo.ORDER_STATUS_ENUM['UNSEND'])
            # 商城购物车数据
            # user = request.user
            # redis_conn = get_redis_connection("carts")
            # #     4.2 删除数据
            # # redis_conn.hdel("carts_%s"%user.id,sku_id)
            # # redis_conn.srem("carts_%s"%user.id,sku_id)
            # pl = redis_conn.pipeline()
            # # 删除键，就等价于删除了整条记录
            # pl.hdel('carts_%s' % user.id, sku_id)
            # pl.srem('selected_%s' % user.id, sku_id)
            # pl.execute()
        context = {
            'trade_id':trade_no
        }
        #     4.3 返回响应
        return render(request,'pay_success.html',context=context)
